package com.flainsky.nirvanaplayer.adpters;

import java.util.List;

import org.videolan.vlc.android.VideoPlayerActivity;

import com.flainsky.nirvanaplayer.R;
import com.flainsky.nirvanaplayer.cache.ImageCache;
import com.flainsky.nirvanaplayer.globe.DownloadUtils;
import com.flainsky.nirvanaplayer.globe.GlobeCache;
import com.flainsky.nirvanaplayer.globe.PlayController;
import com.flainsky.nirvanaplayer.globe.DownloadUtils.DataType;
import com.flainsky.nirvanaplayer.lib.objects.Movie;
import com.flainsky.nirvanaplayer.views.MovieInfoRelativeLayout;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;

public class ShowGridAdapter extends BaseAdapter{

	private Context mContext;
	private List<Movie> mList;
	private ImageCache cache;
	ProgressDialog pdialog;
	
	public ShowGridAdapter(Context context,List<Movie> list)
	{
		mContext = context;
		mList = list;
		cache = GlobeCache.getInstance().getCache();
		
    	pdialog = new ProgressDialog(mContext);
    	pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int i) {
	        	 dialog.cancel();
	         }
	    });
    	pdialog.setTitle(R.string.wait);
        pdialog.setCancelable(true);
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	}
	
	public void setList(List<Movie> list)
	{
		mList = list;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if(mList == null)
			return 0;
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		if(mList == null)
			return null;
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		if(mList == null)
			return 0;
		return mList.get(position).mId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final Movie info = mList.get(position);
		if(convertView == null)
		{
			//LayoutInflater inflater=LayoutInflater.from(mContext);
			convertView  = new MovieInfoRelativeLayout(mContext, null);//inflater.inflate(R.layout.movie_info_item, null);
			((MovieInfoRelativeLayout)convertView).setTitle(info.mTitle);
			((MovieInfoRelativeLayout)convertView).setRb(info.mComment);
			((MovieInfoRelativeLayout)convertView).setImageResource(R.drawable.loading2);
			((MovieInfoRelativeLayout)convertView).getImageView().setTag(info.mSimage);
			if(cache.containsKey(info.mId))
			{
				((MovieInfoRelativeLayout)convertView).getImageView().setImageBitmap(cache.get(info.mId));
			}
			DownloadImageAsyncTask diat = new DownloadImageAsyncTask(info.mSimage,((MovieInfoRelativeLayout)convertView).getImageView(),info.mId);
			diat.execute();
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//PlayController.getInstance().setCurrentPlayUrl(info.mPlay_url);
					PlayController.getInstance().setCurrentPlayMovie(info);
					LoadingVideoAsyncTask loadingVideo = new LoadingVideoAsyncTask();
					loadingVideo.execute();
				}
			});
			
			return convertView;
		}
		else
		{
			MovieInfoRelativeLayout infos = (MovieInfoRelativeLayout)convertView;
			infos.setTitle(info.mTitle);
			infos.setRb(info.mComment);
			infos.setImageResource(R.drawable.loading2);
			infos.getImageView().setTag(info.mSimage);
			if(cache.containsKey(info.mId))
			{
				infos.getImageView().setImageBitmap(cache.get(GlobeCache.MULTIPLE_OF_SMALL*info.mId));
			}
			else
			{
				DownloadImageAsyncTask diat = new DownloadImageAsyncTask(info.mSimage,((MovieInfoRelativeLayout)convertView).getImageView(),info.mId);
				diat.execute();
			}
			
			infos.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					PlayController.getInstance().setCurrentPlayMovie(info);
					//PlayController.getInstance().setCurrentPlayUrl(info.mPlay_url);
					LoadingVideoAsyncTask loadingVideo = new LoadingVideoAsyncTask();
					loadingVideo.execute();
				}
			});
			return infos;
		}
	}
	
	public class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> {

		String mUrl;
		ImageView mIv;
		int mId;
		boolean isFinish = false;
		boolean isNotExit = false;
		public DownloadImageAsyncTask(String url,ImageView iv,int id)
		{
			mUrl = url;
			mIv = iv;
			mId = id;
		}
		@Override
		protected void onPreExecute()
		{
			if(!mUrl.equals(mIv.getTag()))
			{
				isFinish = true;
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if(!isFinish)
			{
				isNotExit = !DownloadUtils.downloadFile(mContext,mUrl,DownloadUtils.DataType.image);
			}
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(isNotExit)
			{
				Toast.makeText(mContext, mUrl+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			if(!mUrl.equals(mIv.getTag()))
			{
				Log.d("cache", mUrl+" out of date");
				return;
			}
			if(mIv!=null)
			{
				if(isFinish)return;
				String str = DownloadUtils.getUrlName(mUrl);
				String path = DownloadUtils.getDataParentPath(DataType.image)+str;
				Bitmap bmp = BitmapFactory.decodeFile(path);
				cache.put(mId*GlobeCache.MULTIPLE_OF_SMALL, bmp);
				mIv.setImageBitmap(bmp);
			}
		}
	}
	
	private void play()
	{
		Intent intent = new Intent(mContext,VideoPlayerActivity.class);
		mContext.startActivity(intent);
	}
	
	public class LoadingVideoAsyncTask extends AsyncTask<Void, Void, Void> {
		
		boolean isNotExit = false;
		public LoadingVideoAsyncTask()
		{
			pdialog.setMessage(mContext.getString(R.string.video_loading));
		}
		
		@Override
		protected void onPreExecute()
		{
			if(pdialog!=null && !pdialog.isShowing())
			{
				pdialog.show();
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			isNotExit = !DownloadUtils.downloadFile(mContext,PlayController.getInstance().getCurrentPlayUrl(), DataType.movie);
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(pdialog != null && pdialog.isShowing())
			{
				pdialog.dismiss();
			}
			if(isNotExit)
			{
				Toast.makeText(mContext, PlayController.getInstance().getCurrentPlayUrl()+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			play();
		}
	}
}
